//
//  OFAuthorizeWebView.m
//  PUDemo
//
//  Created by JK.Peng on 13-2-22.
//  Copyright (c) 2013年 njut. All rights reserved.
//

#import "OFAuthorizeWebView.h"
#import <QuartzCore/QuartzCore.h>

@interface OFAuthorizeWebView ()

@property (nonatomic, retain) UIActivityIndicatorView         *indicatorView;
@property (nonatomic, retain) UIWebView      *authorizeWebView;
@property (nonatomic, retain) UIImageView    *navImageView;

@end

@implementation OFAuthorizeWebView
@synthesize authorizeWebView = _authorizeWebView;
@synthesize indicatorView = _indicatorView;
@synthesize navImageView = _navImageView;
@synthesize delegate = _delegate;

- (void)dealloc{
    _delegate = nil;
    [_navImageView release], _navImageView = nil;
    [_indicatorView release], _indicatorView = nil;
    [_authorizeWebView release], _authorizeWebView = nil;
    [super dealloc];
}

- (id)init
{
    self = [super init];
    if (self) {
        [self.view addSubview:self.authorizeWebView];
        [self.view addSubview:self.indicatorView];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)startAnimatingIndeicatorView
{
    [_indicatorView startAnimating];
}

- (void)cancelAuthorize{
    if ([self.delegate respondsToSelector:@selector(authorizeWebViewDidCancel:)]) {
        [self.delegate authorizeWebViewDidCancel:self];
    }
}

#pragma mark - WBAuthorizeWebView Public Methods
- (void)loadRequestWithURL:(NSURL *)url
{
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url
                                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                      timeoutInterval:60.0];
    [self.authorizeWebView loadRequest:request];
}


#pragma mark - UIWebViewDelegate Methods
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [_indicatorView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_indicatorView stopAnimating];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
        CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
        if (fittingSize.width > kDefaultAuthorizeViewWidthForIpad) {
            //修改服务器页面的meta的值
            NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
            [webView stringByEvaluatingJavaScriptFromString:meta];
        }
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [_indicatorView stopAnimating];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([self.delegate respondsToSelector:@selector(authorizeWebView:startLoadWithParamsString:)]) {
        NSString * url = request.URL.absoluteString;
        NSRange r = [url rangeOfString:@"code="];
        if (r.location != NSNotFound) {
            NSRange range = [url rangeOfString:@"?"];
            if (range.location != NSNotFound) {
                NSString * paramsString = [url substringFromIndex:range.location+range.length];
                [self.delegate authorizeWebView:self startLoadWithParamsString:paramsString];
                return NO;
            }
        }
        
    }
    
    return YES;
}

#pragma mark - getter Methods
- (UIImageView *)navImageView{
    if (!_navImageView) {
        CGFloat width = self.view.bounds.size.width;
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
            width = kDefaultAuthorizeViewWidthForIpad;
        }
        
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, 60)];
        _navImageView.backgroundColor = [UIColor colorWithRed:221.0f green:221.0f blue:221.0f alpha:1.0];
        _navImageView.userInteractionEnabled = YES;
        
        UILabel  *title = [[UILabel alloc] initWithFrame:CGRectMake((_navImageView.bounds.size.width-200)/2, 0,
                                                                    200, _navImageView.bounds.size.height)];
        title.backgroundColor = [UIColor clearColor];
        title.textColor = [UIColor blackColor];
        title.textAlignment = [Util getAlign:ALIGNTYPE_CENTER];
        title.font = [UIFont systemFontOfSize:26.0f];
        title.text = @"授 权";
        [_navImageView addSubview:title];
        [title release];
        
        UIImage *imgBtn = [UIImage imageNamed:@"bg_nav_button_small.png"];
        UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
        btnCancel.exclusiveTouch = YES;
        btnCancel.frame = CGRectMake(width-10-imgBtn.size.width,
                                     (_navImageView.bounds.size.height-imgBtn.size.height)/2,
                                     imgBtn.size.width, imgBtn.size.height);
        [btnCancel setBackgroundImage:imgBtn forState:UIControlStateNormal];
        [btnCancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btnCancel setTitle:@"取消" forState:UIControlStateNormal];
        btnCancel.titleLabel.font = [UIFont systemFontOfSize:16.0f];
        [btnCancel addTarget:self
                      action:@selector(cancelAuthorize)
            forControlEvents:UIControlEventTouchUpInside];
        [_navImageView addSubview:btnCancel];
        
        [self.view addSubview:_navImageView];
    }
    return _navImageView;
}
- (UIWebView *)authorizeWebView{
    if(!_authorizeWebView){
        
        CGFloat height = self.view.bounds.size.height;
        CGFloat width = self.view.bounds.size.width;
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
            height = kDefaultAuthorizeViewHeightForIpad;
            width = kDefaultAuthorizeViewWidthForIpad;
        }
        
        _authorizeWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, self.navImageView.bounds.size.height, width, height-self.navImageView.bounds.size.height)];
        _authorizeWebView.scalesPageToFit = YES;
        [_authorizeWebView setDelegate:self];
        
        for (UIView * subview in _authorizeWebView.subviews) {
            if ([subview isKindOfClass:[UIScrollView class]]) {
                ((UIScrollView *)subview).bounces = NO;
                ((UIScrollView *)subview).showsHorizontalScrollIndicator = NO;
                ((UIScrollView *)subview).showsVerticalScrollIndicator = NO;
            }
        }
        
    }
    return _authorizeWebView;
}

- (UIActivityIndicatorView *)indicatorView{
    if(!_indicatorView){
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [_indicatorView setCenter:self.authorizeWebView.center];
    }
    return _indicatorView;
}


@end
